package com.runjian.rundo.iot.agent.iec104.parser.frame;

import cn.hutool.core.collection.ListUtil;
import com.runjian.rundo.iot.agent.iec104.consts.Action;
import com.runjian.rundo.iot.agent.iec104.consts.FrameType;
import com.runjian.rundo.iot.agent.iec104.enums.UFrameControlType;

import cn.hutool.core.util.StrUtil;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;

import java.util.Arrays;
import java.util.List;

/**
 * U格式 帧
 *
 * @author CaoQingHua
 */
@Getter
@Setter
public class UIec104Frame extends AIec104Frame {

    private UFrameControlType function;

    public UIec104Frame() {
        this.setFrameType(FrameType.U);
    }

    public UFrameControlType getFunction() {
        return function;
    }

    public void setFunction(UFrameControlType function) {
        this.function = function;
    }

    @Override
    public String console() {
        return StrUtil.format("U帧 功能:{}", function.toString());
    }

    /**
     * 回复侦
     * 
     * @return
     */
    @Override
    public AIec104Frame replyFrame() {
        if (null == function && function.getCode() > 0) {
            return null;
        }
        if (function.getDownCode() <= 0) {
            return null;
        }
        // 拼装回复侦
        this.function = UFrameControlType.get(function.getDownCode());
        return this;
    }

    /**
     * 拼装ByteBuf
     * 
     * @return
     */
    @Override
    public ByteBuf assemblyByteBuf() {
        ByteBuf commandByteBuf = super.assemblyByteBuf();
        commandByteBuf.writeBytes(new byte[] {(byte)((function.getCode() << 2) + 3), 0, 0, 0});
        return commandByteBuf;
    }

    @Override
    public List<Action> action() {
        if(this.function==UFrameControlType.STARTDT_V){
            return Arrays.asList(Action.SCHEDULED_C_IC_NA_1);
        }else{
            return null;
        }
    }
}
